import {
  http
} from '@/utils/commonRequest.js'; // 局部引入
import promise from '@/utils/promise.js'
import {
  MAX_INACTIVE_INTERVAL,
	baseUrl
} from '@/utils/constant.js'

let app = getApp()
// #ifdef MP-WEIXIN
  let saveCsrfToken = function(header) {
    var cookie_str;
    for (var key in header) {
      if ('set-cookie' == key.toLowerCase()) {
        cookie_str = header[key];
        break;
      }
    }
    if (null == cookie_str || undefined == cookie_str) {
      return;
    }
    var start = cookie_str.indexOf('csrf_token');
    var end;
    var csrfTokenT;
    while (start > -1) {
      end = cookie_str.indexOf(';', start);
      if (end == -1) {
        end = cookie_str.length;
      }
      csrfTokenT = cookie_str.substring(start + 'csrf_token'.length + 1, end);
      if (null != csrfTokenT && 'null' != csrfTokenT && '' != csrfTokenT && undefined != csrfTokenT) {
        wx.setStorageSync("LOGIN_CSRFTOKEN", csrfTokenT);
        console.log('CSRF ' + wx.getStorageSync("LOGIN_CSRFTOKEN"));
        return;
      }
      start = cookie_str.indexOf('csrf_token', end);
    }
  }
/**
 * 登录
 */
  let login = function() {
		console.log('check===登录方法===============check============================')
    wx.setStorageSync("LOGIN_LOGIN", "expire");
    wx.removeStorageSync("LOGIN_LASTTIME");
    wx.removeStorageSync("LOGIN_JSESSIONID");
    wx.removeStorageSync("LOGIN_CSRFTOKEN");
    let that = getApp()
    
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          let code = res.code;
					let login_memberId = uni.getStorageSync('login_memberId');
					let dataObj = {
						code: code,
						appid: uni.getAccountInfoSync().miniProgram.appId
					}
					if(login_memberId){
						dataObj.memberId = login_memberId;
					}
          wx.request({
            url: baseUrl + '/miniapp/loginNotAuthPlat',
            data: dataObj,
            success: res => {
              console.log('登录成功======',res);
              if (res.data.login == "login" || res.data.login == "authed") {
                wx.setStorageSync("LOGIN_LOGIN", res.data.login);
                wx.setStorageSync("LOGIN_LASTTIME", new Date());
                wx.setStorageSync("LOGIN_JSESSIONID", res.data.JSESSIONID);
								uni.setStorageSync('memberInfo', res.data.memberInfo);
								uni.setStorageSync('openid', res.data.openid)
								uni.setStorageSync('noApproveFlag',res.data.memberInfo && res.data.memberInfo.approve != '1')
                console.log(res.data.JSESSIONID,777777777)
                that.globalData.memberInfo = (res.data.login == "authed") ? res.data.memberInfo : null;
                that.globalData.platId = (res.data.login == "authed") ? res.data.platId : null
								uni.setStorageSync("platType", res.data.platType)
                that.globalData.platType = res.data.platType;
								uni.setStorageSync("platName", res.data.platName || null)
								uni.$emit('loginUpdate')
                saveCsrfToken(res.header);
                resolve(res.data.login);
              } else {
                reject("failed");
              }
            },
            fail: (err) => {
              console.log(err);
              reject("failed");
            }
          })
        },
        fail: function (err) {
          console.log(err);
          reject("failed");
        }
      })
    });
  }

  /**
   * 检查登录
   */
  let checkLogin = function() {
    let app = getApp()
    let that = this;
    return new promise((resolve, reject) => {
      
      var logins = wx.getStorageSync("LOGIN_LOGIN");
      var lastTime = wx.getStorageSync("LOGIN_LASTTIME");
      
      if (typeof lastTime == "object") {
        lastTime = lastTime.getTime();
      };
      console.log(app,'执行登录11')
      let memberInfo = app.globalData.memberInfo
      console.log('===',logins)
      if (("login" == logins || "authed" == logins) && ((new Date()).getTime() - lastTime) < (app.globalData.MAX_INACTIVE_INTERVAL - 30) * 1000) {
				console.log('执行登录1')
				const resObj = { status: logins, type: 'confrim' }
        // resolve(logins);
				resolve(resObj);
        
      } else {
        //登录超时,重新登录
        console.log('执行登录2')
				const resObj = { status: logins, type: 'update' }
        // login().then(res => resolve(res)).catch(err => reject(err));
				 login().then(res => resolve(resObj)).catch(err => reject(err));
      }
    });
  }

  /**
   * 检查认证
   * navType注册成功后跳转类型：redirect/switchTab/navigateBack/navigateTo
   * navUrl注册成功后跳转页面
   */
   let checkAuth = function (navType, navUrl) {
    console.log("checkAuth",navType);
    let app = getApp()
    return new Promise((resolve, reject) => {
      checkLogin().then(res => {
				console.log('0000--checkAuth',res)
        if ('authed' == res.status || 'expire' == res.status) {
          //已认证 or session过期
          resolve(res.status);
        }else {
          wx.removeStorageSync("NAV_TYPE_AFTER_REGIST");
          wx.removeStorageSync("NAV_URL_AFTER_REGIST");
          if (undefined != navType && "navigateBack" != navType) {
            wx.setStorageSync("NAV_TYPE_AFTER_REGIST", navType);
            wx.setStorageSync("NAV_URL_AFTER_REGIST", navUrl);
          }
					var url = '/pages/regist/regist';
          if ("navigateBack" == navType || "navigateTo" == navType) {
            wx.navigateTo({
              url: url
            })
          } else {
            wx.redirectTo({
              url: url
            })
          }
        }
      }).catch(err => {
        reject(err);
      })
    });
  }


// #endif
// #ifdef H5 || MP-UNIONPAY


let checkLogin = function() {
  let that = this
  let lastTime = uni.getStorageSync("LOGIN_LASTTIME");
  if (typeof lastTime == "object") {
    lastTime = lastTime.getTime();
  }
  return new Promise((resolve, reject) => {
    if (((new Date()).getTime() - lastTime) < (MAX_INACTIVE_INTERVAL - 30) * 1000) {
      resolve()
      return
    }
    http.get('/auth/checkLogin', {})
      .then(res => {
        if (200 == res.data.code) {
          uni.setStorageSync("LOGIN_LASTTIME", new Date());
          uni.setStorageSync("platType", res.data.platType)
          resolve()
        } else {
          reject("failded")
        }
      })
      .catch(err => {
        console.log(err);
        reject("failded")
      });
  })
}

let checkAuth = function() {
  let that = this
  let lastAuthTime = uni.getStorageSync("AUTH_LASTTIME");
  if (typeof lastAuthTime == "object") {
    lastAuthTime = lastAuthTime.getTime();
  }
  let sessionMemberInfo = uni.getStorageSync('memberInfo')
  return new Promise((resolve, reject) => {
    if (((new Date()).getTime() - lastAuthTime) < (MAX_INACTIVE_INTERVAL - 30) * 1000 && sessionMemberInfo) {
      resolve()
      return
    }
    uni.removeStorageSync("AUTH_LASTTIME")
    uni.removeStorageSync('memberInfo')
    http.get('/auth/checkAuth', {})
      .then(res => {
        if (200 == res.data.code) {
          uni.setStorageSync("AUTH_LASTTIME", new Date()); //上次登录时间
          let memberInfo = res.data.memberInfo
          uni.setStorageSync('memberInfo', memberInfo)
          resolve()
        } else {
          reject("failded")
        }
      })
      .catch(err => {
        console.log(err);
        reject("failded")
      });
  })
}
// #endif

module.exports = {
  checkLogin: checkLogin,
  checkAuth: checkAuth
}
